import puppeteer, { Page, Browser } from 'puppeteer';
import EventEmitter from "events";
import { UserAgent } from '../../config/variable';
import { getQrCode } from '../thirdServices/museumApi';
class MuseumLogin {
  _page: Page | undefined;
  _browser: Browser | undefined;
  id = new Date().getTime()
  
  constructor() {
  }

  async init(ip?: string){
    let options: any = {
        headless: true
    };

    options.args = ['--no-sandbox', '--disable-setuid-sandbox'];

    if (ip) {
        options.args.push(`--proxy-server=${ip}`);
    }
    // const browser = await puppeteer.launch({headless: false});
    const browser = await puppeteer.launch(options);
    this._browser = browser;
    const page = await browser.newPage();
    this._page = page;
    await page.setUserAgent(UserAgent);
    await page.setViewport({width: 1366, height: 768});
  }

  async getQrCode(): Promise<string> {
    const res = await getQrCode();
    let url = '';
    if (res.data.code === 200) {
      url = res.data.data;
    } else {
      throw new Error(res.data.message);
    }

    if (this._page) {
      const page = this._page;
      await page.goto(url);
      await page.addScriptTag({ 'path': 'lib/stealth.min.js' });
      await page.waitForSelector('.qrcode', { timeout: 60 * 1000 }); // 获取iframe元素的句柄，等待一分钟
      const qrcode = await page.$eval("img.qrcode", (element) => element.getAttribute("src"));
      return qrcode || '';
    }

    return '';
  }

  async awaitAddUser(emitter: EventEmitter) {
    if (this._page) {
      try {
        await this._page.waitForSelector('.float-box.small-box');
        const url = this._page.url();
        const params = new URLSearchParams(url.split('?')[1]);
        const token = params.get('token')?.split('&')[0];
        if (this._browser) {
          this._browser.close();
        }
        emitter.emit('addMuseumUser', {
          token, 
          id: this.id
        }); 
      } catch (error) {
        if (this._browser) {
          this._browser.close();
        }
        emitter.emit('addMuseumUser', this.id);
      }
    }
  }
}

export default MuseumLogin;